<?php
namespace App\Repository\Db;

use App\Exceptions\ValidateException;
use App\Repository\Contracts\UserInterface;
use App\Support\Helper\CommonHelper;

/**
 * @Author:: HuangYin
 * @DateTime: 2017/6/7 22:35
 */
class UserRepository extends Repository implements UserInterface
{
    protected $rules = [
        'created' => [
            'phone' => 'required|regex:/^1[34578][0-9]{9}$/|unique:user,phone'
        ],
        'updated' => [
            'phone' => 'sometimes|regex:/^1[34578][0-9]{9}$/|unique:user',
            'nickname' => 'sometimes|min:2|max:10',
            'real_name' => 'sometimes|min:2|max:16',
            'studentId' => 'sometimes|min:8|max:16',
            'address' => 'sometimes|min:2|max:32',
            'avatar' => 'sometimes|min:8'
        ]
    ];

    protected $messages = [
        'phone.required' => '手机号码不能为空',
        'phone.regex' => '手机号码不合法',
        'phone.unique' => '手机号码已存在',
        'nickname.min' => "昵称不能小于 2 个字",
        'nickname.max' => "昵称不能大于 10 个字",
        'real_name.min' => "真实姓名不能小于 2 个字",
        'real_name.max' => "真实姓名不能大于 16 个字",
        'student_id.min' => "学生证号不能小于 8 个字",
        'student_id.max' => "学生证号不能大于 16 个字",
        'address.min' => "地址不能小于 2 个字",
        'address.max' => "地址不能大于 32 个字",
        'avatar.min' => "图片不能为空",
    ];

    protected function modelName()
    {
        return 'App\Model\User';
    }

    private function created(array $data)
    {
        $this->validate($data, 'created');

        return $this->save($data);
    }

    private function findByPhone($phone)
    {
        return $this->findBy('phone', $phone);
    }

    public function detail($id)
    {
        return $this->find($id);
    }

    public function checkToken($token)
    {
        $result = $this->findBy('token', $token);
        if ($result && CommonHelper::getToken($result->token)['prefix'] == 'frontend') {

            return $result->token;
        }

        return null;
    }

    public function login(array $data)
    {
        if (!$user = $this->findByPhone($data['phone'])) {
            $userId = $this->created($data);
            $user = $this->detail($userId);
        }

        $token = CommonHelper::setToken(json_encode(['uid' => $user->id, 'prefix' => 'frontend']));
        $this->update(['token' => $token], $user->id, 'id');
        $result = $user->toArray();
        $result['token'] = $token;

        return $result;
    }

    public function updated($id, array $data)
    {
//        $this->validate($data, 'created');
        return $this->update($data, $id, 'id');
    }

    public function logout($uid)
    {
        return $this->update(['token' => ''], $uid, 'id');
    }
}